import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
    Switch,
    Row,
    Col,
    Card,
    Progress,
    Statistic,
    Typography,
    Space,
    Button,
    message,
    Tooltip,
    Tag,
} from "antd";
import {
    DeploymentUnitOutlined,
    PlayCircleOutlined,
    CloudOutlined,
    DashboardOutlined,
    DatabaseOutlined,
    ProductOutlined,
    CloudUploadOutlined,
    BarsOutlined,
    SyncOutlined,
    InfoCircleOutlined,
} from "@ant-design/icons";
import { postBindInfo } from "@/services/nodes/api";
import styles from "./Localhost.module.css";
import {
    postReaload,
    postBasicInfo,
} from "@/services/nodes/api";

const Localhost: React.FC = () => {
    const { Title, Text } = Typography;
    const [time, setTime] = useState("");
    const [space, setSpace] = useState("");
    const [load, setLoad] = useState({
        cpuLoad: 0,
        memoryUsage: 0,
        diskUsage: 0,
    });
    const [hostingCount, setHostingCount] = useState({
        all: 0,
        live: 0,
        deploy: 0,
    });
    const [systemInfo, setSystemInfo] = useState<any>([]);
    const [compileStatus, setCompileStatus] = useState<any>([]);
    const initNodeId = () => { 
        const param = new URLSearchParams(window.location.search);
        const temp_id = param.get("node_id")
        if (temp_id === null) {
            return "0";
        } else {
            return temp_id;
        }
    };
    const selectNodeID = initNodeId()
    // 初始化数据
    useEffect(() => {

        const initBasicInfo = async () => {
            await postBasicInfo(selectNodeID)
                .then((res: any) => {
                    const data = res.message;
                    setTime(data.realtime);
                    setSpace(data.fm_occ_space);
                    setHostingCount(data.hosting_count);
                    setSystemInfo(data.system_info);
                    setCompileStatus(data.compile_status);
                })
                .catch((err: any) => {
                    message.error(err.message);
                });
        };

        // 初始化时获取数据
        initBasicInfo();

        // 每30秒请求一次基础信息（除系统负载外的所有信息）
        const basicInfoTimer = setInterval(() => {
            initBasicInfo();
        }, 30000);

        // 每秒更新时间（本地计算）
        const timer = setInterval(() => {
            setTime((prevTime) => {
                if (prevTime) {
                    // 尝试解析时间字符串
                    const date = new Date(prevTime);
                    // 检查日期是否有效
                    if (!isNaN(date.getTime())) {
                        date.setSeconds(date.getSeconds() + 1);
                        // 格式化为API返回的时间格式: yyyy/MM/dd HH:mm:ss
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(
                            2,
                            "0",
                        );
                        const day = String(date.getDate()).padStart(2, "0");
                        const hours = String(date.getHours()).padStart(2, "0");
                        const minutes = String(date.getMinutes()).padStart(
                            2,
                            "0",
                        );
                        const seconds = String(date.getSeconds()).padStart(
                            2,
                            "0",
                        );
                        return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
                    }
                }
                return prevTime;
            });
        }, 1000);

        // 获取系统负载信息
        const initReaload = async () => {
            await postReaload(selectNodeID)
                .then((res: any) => {
                    setLoad({
                        cpuLoad: res.message.cpu,
                        memoryUsage: res.message.mem,
                        diskUsage: res.message.disk,
                    });
                })
                .catch((err: any) => {
                    message.error(err.message);
                });
        };
        // 初始化时获取数据
        initReaload();

        // 每5秒请求一次系统负载信息
        const loadTimer = setInterval(() => {
            initReaload();
        }, 5000);


        // 清理定时器
        return () => {
            clearInterval(timer);
            clearInterval(loadTimer);
            clearInterval(basicInfoTimer);
        };
    }, []);

    const [autoStartEnabled, setAutoStartEnabled] = useState<boolean>(false);
    const navigate = useNavigate();

    const copyBindInfo = async () => {
        return await postBindInfo(navigate)
            .then((res: any) => {
                let bindInfoText = "";
                if (res.message && typeof res.message === "object") {
                    if (res.message.certificate) {
                        bindInfoText =
                            typeof res.message.certificate === "string"
                                ? res.message.certificate
                                : JSON.stringify(res.message.certificate);
                    } else {
                        bindInfoText = JSON.stringify(res.message);
                    }
                } else {
                    bindInfoText = res.message || "";
                }
                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard
                        .writeText(bindInfoText)
                        .then(() => {
                            message.info("复制成功！");
                        })
                        .catch((err) => {
                            message.error("复制失败: " + err);
                        });
                } else {
                    try {
                        const textArea = document.createElement("textarea");
                        textArea.value = bindInfoText;
                        document.body.appendChild(textArea);
                        textArea.focus();
                        textArea.select();
                        document.execCommand("copy");
                        document.body.removeChild(textArea);
                        message.info("复制成功！");
                    } catch (err) {
                        message.error("复制失败: " + err);
                    }
                }
            })
            .catch((error: any) => {
                message.error(error.message);
            });
    };
    return (
        <div
            className={styles.container}
            style={{
                padding: "24px",
                maxHeight: "85vh",
                overflowY: "auto",
                position: "relative",
            }}
        >
            <Card
                title={
                    <Space>
                        <BarsOutlined />
                        <span>主要信息</span>
                    </Space>
                }
                extra={<Button onClick={copyBindInfo}>复制绑定信息</Button>}
                style={{ marginBottom: "20px" }}
            >
                <Row gutter={[16, 16]}>
                    <Col xs={24} sm={8} md={8}>
                        <Card size="small">
                            <Statistic title="服务器时间" value={time} />
                        </Card>
                    </Col>
                    <Col xs={24} sm={8} md={8}>
                        <Card size="small">
                            <Statistic
                                title="渔翁及数据占用磁盘空间"
                                value={space}
                            />
                        </Card>
                    </Col>
                    <Col xs={24} sm={8} md={8}>
                        <Card size="small">
                            <Statistic
                                title="开机自启动"
                                value=""
                                valueStyle={{
                                    visibility: "hidden",
                                    height: 0,
                                    margin: 0,
                                    padding: 0,
                                }}
                            />
                            <div style={{ marginBottom: "13px" }}></div>
                            <Tooltip title={"功能开发中..."}>
                                <Switch
                                    disabled
                                    checked={autoStartEnabled}
                                    onChange={setAutoStartEnabled}
                                    checkedChildren="启用"
                                    unCheckedChildren="未启用"
                                />
                            </Tooltip>
                        </Card>
                    </Col>
                </Row>
            </Card>

            {/* 系统负载区域 */}
            <Card
                title={
                    <Space>
                        <CloudOutlined />
                        <span>系统负载</span>
                    </Space>
                }
                // extra={
                //     <>
                //         <Button style={{marginRight:"15px"}}>额外占用</Button>
                //         <Button>任务监视器</Button>
                //     </>

                // }
                style={{ marginBottom: "20px" }}
            >
                <Row gutter={[16, 16]}>
                    <Col xs={24} sm={12} md={8}>
                        <Card size="small">
                            <Statistic
                                title="CPU使用率"
                                value={load.cpuLoad}
                                suffix="%"
                                prefix={<DeploymentUnitOutlined />}
                            />
                            <Progress
                                percent={load.cpuLoad}
                                status="active"
                                strokeColor={"#5352ed"}
                            />
                        </Card>
                    </Col>
                    <Col xs={24} sm={12} md={8}>
                        <Card size="small">
                            <Statistic
                                title="内存使用率"
                                value={load.memoryUsage}
                                suffix="%"
                                prefix={<DatabaseOutlined />}
                            />
                            <Progress
                                percent={load.memoryUsage}
                                status="active"
                                strokeColor={"#5352ed"}
                            />
                        </Card>
                    </Col>
                    <Col xs={24} sm={12} md={8}>
                        <Card size="small">
                            <Statistic
                                title="根目录分区使用率"
                                value={load.diskUsage}
                                suffix="%"
                                prefix={<DatabaseOutlined />}
                            />
                            <Progress
                                percent={load.diskUsage}
                                status="active"
                                strokeColor={"#5352ed"}
                            />
                        </Card>
                    </Col>
                </Row>
            </Card>
            <Card
                title={
                    <Space>
                        <ProductOutlined />
                        <span>托管应用统计</span>
                    </Space>
                }
                // extra={
                //     <>
                //         <Button style={{marginRight:"15px"}}>导入</Button>
                //         <Button>导出</Button>
                //     </>
                // }
                style={{ marginBottom: "20px" }}
            >
                <Row gutter={[16, 16]}>
                    <Col xs={24} sm={8} md={8}>
                        <Card size="small">
                            <Statistic
                                title="应用总数"
                                value={hostingCount.all}
                                prefix={<DeploymentUnitOutlined />}
                            />
                        </Card>
                    </Col>
                    <Col xs={24} sm={8} md={8}>
                        <Card size="small">
                            <Statistic
                                title="运行中应用"
                                value={hostingCount.live}
                                prefix={<PlayCircleOutlined />}
                                valueStyle={{ color: "#2ed573" }}
                            />
                        </Card>
                    </Col>
                    <Col xs={24} sm={8} md={8}>
                        <Card size="small">
                            <Statistic
                                title="发布总数"
                                value={hostingCount.deploy}
                                prefix={<CloudUploadOutlined />}
                            // valueStyle={{ color: "#3f8600" }}
                            />
                        </Card>
                    </Col>
                </Row>
            </Card>
            <Card
                title={
                    <Space>
                        <SyncOutlined />
                        <span>自编译软件状态</span>
                        <Tooltip title="区别于其他已安装软件，为避免发生冲突，不建议脱离渔翁单独使用。">
                            <Button
                                type="text"
                                icon={
                                    <InfoCircleOutlined
                                        style={{ fontSize: "16px" }}
                                    />
                                }
                                style={{
                                    display: "flex",
                                    alignItems: "center",
                                }}
                            />
                        </Tooltip>
                    </Space>
                }
                // extra={
                //     <>
                //         <Button>重编译</Button>
                //     </>
                // }
                style={{ marginBottom: "20px" }}
            >
                <Row gutter={[16, 16]}>
                    {compileStatus.map((service: any, index: any) => (
                        <Col xs={24} sm={12} md={8} key={index}>
                            <Card size="small">
                                <Statistic
                                    title={
                                        service.name
                                    }
                                    value=""
                                    valueStyle={{
                                        visibility: "hidden",
                                        height: 0,
                                        margin: 0,
                                        padding: 0,
                                    }}
                                />
                                <div style={{ marginBottom: "13px" }}></div>
                                {service.status === "True" ? (
                                    <Tag
                                        color="success"
                                    >
                                        {'编译成功'}
                                    </Tag>
                                ) : (
                                    <Tag
                                        color="error"
                                    >
                                        {'编译失败'}
                                    </Tag>
                                )}

                            </Card>
                        </Col>
                    ))}
                </Row>
            </Card>

            {/* 操作系统信息区域 */}
            <Card
                title={
                    <Space>
                        <DashboardOutlined />
                        <span>操作系统信息</span>
                    </Space>
                }
            >
                <Row gutter={[16, 16]}>
                    {systemInfo.map((env: any, index: any) => (
                        <Col xs={24} sm={12} md={12} key={index}>
                            <div
                                style={{
                                    display: "flex",
                                    justifyContent: "space-between",
                                }}
                            >
                                <Text strong>{env.name}:</Text>
                                <Text>{env.value}</Text>
                            </div>
                        </Col>
                    ))}
                </Row>
            </Card>
        </div>
    );
};

export default Localhost;
